package com.chuanke.ckfamily.service.social.impl;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.chuanke.ckfamily.service.common.exception.LockException;
import com.chuanke.ckfamily.service.exception.FamilyCaptionMaxCaption;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chuanke.ckfamily.dao.base.Page;
import com.chuanke.ckfamily.dao.social.FamilyMemberDao;
import com.chuanke.ckfamily.dao.social.model.Family;
import com.chuanke.ckfamily.dao.social.model.FamilyMember;
import com.chuanke.ckfamily.dao.social.model.MemberMute;
import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.base.FailCode;
import com.chuanke.ckfamily.service.base.FamilyValidator;
import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.common.CacheService.KEY_PREFIX;
import com.chuanke.ckfamily.service.common.SysConfigService;
import com.chuanke.ckfamily.service.common.TipsService;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.common.impl.RedisLockUtil;
import com.chuanke.ckfamily.service.constant.Constant.MemberDeleteEnum;
import com.chuanke.ckfamily.service.constant.FamilyConstance;
import com.chuanke.ckfamily.service.constant.SysConfigKeyEnum;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.exception.FamilyExcepiton;
import com.chuanke.ckfamily.service.social.FamilyMemberService;
import com.chuanke.ckfamily.service.social.FamilyService;
import com.chuanke.ckfamily.service.user.UserService;
import com.weijie.core.BaseBiz;
import com.weijie.core.wy.WyHelper;
import com.weijie.core.wy.model.TeamJoinTeams;
import com.weijie.core.wy.response.WyTeamJoinTeamsResponse;
import com.weijie.corel.wy.request.WyTeamJoinTeamsRequest;

@Service
@Transactional(rollbackFor = Exception.class)
public class FamilyMemberServiceImpl extends BaseBiz<FamilyMember, FamilyMemberDao> implements FamilyMemberService {

	private static final Logger log = LoggerFactory.getLogger(FamilyMemberServiceImpl.class);

	private final String Lock_memberMute = "mute_member_";

	@Autowired
	private UserService userService;

	@Autowired
	private FamilyService familyService;

	@Autowired
	private WyService wyService;

	@Autowired
	private TipsService tipsService;

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private CacheService cacheService;
	
	@Override
	public void save(FamilyMember entity) {
		super.save(entity);
		saveOrDeleteMember(entity);
	}
	@Override
	public void update(FamilyMember entity) {
		super.update(entity);
		saveOrDeleteMember(entity);
	}
	
	private void saveOrDeleteMember(FamilyMember entity) {
		Long user_id = entity.getUser_id();
		Integer is_delete = entity.getIs_delete();
		if(is_delete!=null && user_id != null){
			if(is_delete == 0 ){
				cacheService.set(CacheService.KEY_PREFIX.familyMember_.name() + entity.getUser_id(), entity);
			}else if(is_delete == 1){
				cacheService.delete(CacheService.KEY_PREFIX.familyMember_.name() + entity.getUser_id());
			}
		}
	}

	@Override
	public List<User> getTopMembers(Long familId) throws CFException {
		Family family = familyService.findById(familId);
		if (family == null) {
			throw new CFException(FailCode.FAMILY_NOT_EXIST);
		}

		List<User> topMemberList = new ArrayList<>(8);
		topMemberList.add(userService.findById(family.getOwner_user_id()));

		List<User> topUsers = baseDao.findTopMembers(familId);
		for (User member : topUsers) {
			if (member.getId().longValue() == family.getOwner_user_id()) {
				continue;
			}
			topMemberList.add(member);
		}

		return topMemberList;
	}

	@Override
	public List<User> getMembers(Long familyId) {
		return baseDao.findMembers(familyId);
	}

	@Override
	public FamilyMember findByUserId(Long userId) {
		if (userId == null) {
			return null;
		}
		return baseDao.findByUserId(userId);
	}

	@Override
	public Integer searchCountByFamilyId(Long familyId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("family_id", familyId);

		return baseDao.searchCount(param);
	}

	@Override
	public List<User> getCanAddMember(Long userId, String nickName, Page page, String tid) throws CFException {
		Family family = familyService.findFamilyByUserId(userId);
		FamilyValidator.validateFamilyTid(family, tid);

		return findCanAddMember(userId, nickName, page, family.getId());
	}

	private List<User> findCanAddMember(Long userId, String nickName, Page page, Long familyId) {
		Map<String, Object> param = new HashMap<>();
		param.put("super_id", userId);
		param.put("familyId", familyId);
		if (StringUtils.isNotEmpty(nickName)) {
			param.put("nickName", nickName);
		}

		log.info("findCanAddMember==========>param={}", param);
		return baseDao.getCanAddMember(param, page);
	}

	@Override
	public int addFamilyMembers(Long uid, List<String> fanList, Boolean oneKey, String tid) throws CFException {
		Family family = familyService.findFamilyByUserId(uid);
		FamilyValidator.validateFamilyTid(family, tid);

		Integer capacity = family.getFcapacity();
		if (capacity == null) {
			capacity = sysConfigService.getIntegerValue(SysConfigKeyEnum.user_family_max.name(), FamilyConstance.FAMILY_CAPACITY);
		}

		Integer memberCount = this.searchCountByFamilyId(family.getId());
		if (memberCount >= capacity) {
			throw new FamilyExcepiton(FailCode.APP, "已达到家族上限");
		}

	
		List<User> fansUserList = null;
		if (oneKey != null && oneKey.booleanValue()) {
			fansUserList = findCanAddMember(uid, null, new Page(0, capacity - memberCount), family.getId());
			if (fansUserList == null || fansUserList.isEmpty()) {
				throw new FamilyExcepiton(FailCode.APP, "没有待邀请的粉丝");
			}

		} else if (fanList != null) {
			fansUserList = new ArrayList<>(10);
			for (String str : fanList) {
				Long fid = Long.parseLong(str);
				User fans = userService.findById(fid);
				if (fans.getSuper_id() == null || fans.getSuper_id().longValue() != uid) {
					continue;
				}

				if (fans.getIs_header() != null && fans.getIs_header() == 1) {
					continue;
				}

				fansUserList.add(fans);
			}

		}

		return addFamilyMembers(family, fansUserList, false);

	}

	@Override
	public boolean addFamilyMember(Family family, User user, boolean saveToWy, boolean auto) throws CFException {
		if (family == null) {
			throw new CFException(FailCode.FAMILY_NOT_EXIST);
		}

		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}

		try {
			if (!addMemberRecord(family, user, auto)) {
				return false;
			}

			if (saveToWy && user.hasWyId()) {
				wyService.addTeamMember(family, user.getUser_no());
			}

			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;

		}
	}

	@Override
	public int addFamilyMembers(Family family, List<User> users, boolean auto) throws CFException {
		List<String> userUnList = new ArrayList<>(users.size() / 10);
		int num = 0;
		for (User user : users) {
			if (user.getIs_header() != null && user.getIs_header() == 1) {
				continue;
			}

			RedisLockUtil lockUtil = null;
			try {
				lockUtil = cacheService.getLock(KEY_PREFIX.move_user_.name() + user.getId());
				boolean addResult = false;
				try {
					addResult = addMemberRecord(family, user, auto);

				} catch (FamilyCaptionMaxCaption e) {
					e.printStackTrace();
					break;

				}

				if (addResult) {
					if (user.hasWyId()) {
						userUnList.add(user.getUser_no());
					}

					num++;

				} else {
					continue;

				}

			} catch (Exception e) {
				e.printStackTrace();

			} finally{
				if(lockUtil!=null){
					lockUtil.unlock();
				}

			}
		}

		wyService.addTeamMembers(family, userUnList);
		return num;
	}

	@Override
	public int kickFamilyMember(Long ownerId, List<String> members, String tid) throws CFException, Exception {
		if (members == null || members.isEmpty()) {
			throw new FamilyExcepiton(FailCode.PARAMS_ERROR);
		}
		Family family = familyService.findFamilyByUserId(ownerId);
		FamilyValidator.validateFamilyTid(family, tid);

		int result = 0;
		for (String str : members) {
			RedisLockUtil lockUtil = null;
			boolean leave = false;
			try {
				Long mid = Long.valueOf(str);
				FamilyMember member = findByUserId(mid);
				if (member == null) {
					continue;
				}
				if (family.getId().longValue() != member.getFamily_id().longValue()) {
					continue;
				}

				long currentTimeMillis = System.currentTimeMillis();
				long kick_login_time = sysConfigService.getLongValue(SysConfigKeyEnum.kick_login_time.toString(), FamilyConstance.LEADER_LOST_TIME_SPAN);
//				long create_time = member.getCreate_time().getTime();
				User tuser = userService.findById(mid);

				if (tuser.getActive_time() != null) {
					long loginTime = tuser.getActive_time().getTime();
					boolean is_kick = (currentTimeMillis - loginTime > kick_login_time);
					if (!is_kick) {
						continue;
					}

				} 

				
				int deleteType = MemberDeleteEnum.kick.getType();

				lockUtil = cacheService.getLock(KEY_PREFIX.move_user_.name() + member.getUser_id());
				
				leave = leaveFamily(member, true, deleteType);
				++result;
				
			} catch (Exception e) {
				e.printStackTrace();
				if(leave){
					lockFamilyCaption(family.getId(), false);
				}
			}finally {
				if (lockUtil != null) {
					lockUtil.unlock();
				}

			}

		}

		return result;
	}

	@Override
	public boolean leaveFamily(Long uid, boolean force, String tid) throws Exception {
		FamilyMember member = findByUserId(uid);
		if (member == null) {
			return true;
		}

		Family family = familyService.findById(member.getFamily_id());
		if (family == null) {
			baseDao.delete(member);
			return true;
		}

		if (!force) {
			User ower = userService.findById(family.getOwner_user_id());
			long leave_login_time = sysConfigService.getLongValue(SysConfigKeyEnum.leave_login_time.toString(), FamilyConstance.LEADER_LOST_TIME_SPAN);
			if (ower.getActive_time() != null && System.currentTimeMillis() - ower.getActive_time().getTime() < leave_login_time) {
				throw new CFException(FailCode.APP, "不可以退出活跃群");
			}
		}

		int deleteType = MemberDeleteEnum.leave.getType();
		RedisLockUtil lockUtil = null;
		try {
			lockUtil = cacheService.getLock(KEY_PREFIX.move_user_.name() + member.getUser_id());
			leaveFamily(member, false, deleteType);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if(lockUtil!=null){
				lockUtil.unlock();
			}
		}
		try {
			familyService.addFamilyBylogin(member.getUser_id(), family.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}

	@Override
	public Map<String, Object> muteFamilyMember(Long userId, Long tuserId, String tid) throws ParseException, IOException, CFException {
		Map<String, Object> result = new HashMap<>();

		FamilyMember tfamilyMember = findByUserId(tuserId);
		if (tfamilyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}

		Family tfamily = familyService.findById(tfamilyMember.getFamily_id());
		FamilyValidator.validateFamilyTid(tfamily, tid);

		FamilyMember familyMember = findByUserId(userId);
		if (familyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		if (!familyMember.getFamily_id().equals(tfamilyMember.getFamily_id())) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		Family family = familyService.findById(familyMember.getFamily_id());
		FamilyValidator.validateFamilyTid(family, tid);

		if (tfamilyMember.getMute() == 1) {
			throw new FamilyExcepiton(FailCode.APP, "对方已经被禁言");
		}

		User user = userService.findById(userId);
		if (user == null) {
			throw new FamilyExcepiton(FailCode.USER_NOT_EXIST);
		}

		User tuser = userService.findById(tuserId);
		if (tuser == null) {
			throw new FamilyExcepiton(FailCode.USER_NOT_EXIST);
		}

		boolean is_owner = userId.equals(family.getOwner_user_id());
		boolean invalidMemberMute = true;

		long muteTimeSpan = sysConfigService.getLongValue(SysConfigKeyEnum.mulit_mute_time.name(), FamilyConstance.MULIT_MUTE_TIME) * 1000;
		int muteNumSpan = sysConfigService.getIntegerValue(SysConfigKeyEnum.mulit_mute_num.name(), FamilyConstance.MULIT_MUTE_NUM);
		String alertMsg = String.format("你已经对他发出禁言指令，%s秒内有%s名非族长成员对TA禁言，即可生效。", String.valueOf(muteTimeSpan / 1000), String.valueOf(muteNumSpan));
		if (!is_owner) {
			MemberMute memberMute = getMemberMute(family.getId(), userId, tuserId);
			if (memberMute != null && (System.currentTimeMillis() - memberMute.getCreate_time().getTime() < muteTimeSpan)) {
				log.warn("muteFamilyMember========>无效禁言.familyId={},userId={},tuserId={},time={}", family.getId(), userId, tuserId, muteTimeSpan);
				// throw new
				// FamilyExcepiton(FailCode.FAMILY_MUTE_ERROR,alertMsg);
				invalidMemberMute = false;
			}
		}

		if (invalidMemberMute) {
			RedisLockUtil lockUtil = null;
			try {
				lockUtil = cacheService.getLock(Lock_memberMute + tuserId);
				if (is_owner) {
					setMemberMute(family, tfamilyMember, tuser, 1);

				} else {
					FamilyMember tmemberParam = new FamilyMember();

					Timestamp mute_time = tfamilyMember.getMute_time();
					Integer mute_num = tfamilyMember.getMute_num() != null ? tfamilyMember.getMute_num() : 0;
					if (mute_time != null && (System.currentTimeMillis() - mute_time.getTime()) < muteTimeSpan) {
						mute_num++;
					} else {
						mute_num = 1;
						tmemberParam.setMute_time(new Timestamp(System.currentTimeMillis()));
					}
					if (mute_num >= muteNumSpan) {
						alertMsg = "";
						setMemberMute(family, tfamilyMember, tuser, 1);

					} else {
						tmemberParam.setId(tfamilyMember.getId());
						tmemberParam.setMute_num(mute_num);
						this.update(tmemberParam);

					}

					saveMemberMute(family.getId(), userId, tuserId);

				}

			} catch (Exception e) {
				e.printStackTrace();

			} finally {
				if (lockUtil != null) {
					lockUtil.unlock();
				}

			}
		}
		result = userService.formatMemberInfoCode(user, tuser, result);
		if (!is_owner) {
			result.put("alertMsg", alertMsg);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	private MemberMute getMemberMute(Long familyId, Long userId, Long tuserId) {
		MemberMute memberMute = (MemberMute) cacheService.get(KEY_PREFIX.member_mute_.toString() + familyId + "_" + tuserId + "_" + userId);
		return memberMute;
	}

	@SuppressWarnings("unchecked")
	private void saveMemberMute(Long familyId, Long userId, Long tuserId) {
		MemberMute memberMute = new MemberMute();
		memberMute.setCreate_time(new Timestamp(System.currentTimeMillis()));
		memberMute.setUpdate_time(new Timestamp(System.currentTimeMillis()));
		memberMute.setUser_id(userId);
		memberMute.setTarget_user_id(tuserId);
		memberMute.setFamily_id(familyId);
		long muteTimeSpan = sysConfigService.getLongValue(SysConfigKeyEnum.mulit_mute_time.name(), FamilyConstance.MULIT_MUTE_TIME) * 1000;
		cacheService.set(KEY_PREFIX.member_mute_.toString() + memberMute.getFamily_id() + "_" + memberMute.getTarget_user_id() + "_" + memberMute.getUser_id(), memberMute, muteTimeSpan);
	}

	@SuppressWarnings("deprecation")
	private void deleteMemberMuteByPrex(Long familyId, Long userId, Long tuserId) {
		cacheService.deleteByPrex(KEY_PREFIX.member_mute_.toString() + familyId + "_" + tuserId + "_" + userId);
	}

	@Override
	public Map<String, Object> unMuteFamilyMember(Long userId, Long tuserId, String tid) throws ParseException, IOException, CFException {
		Map<String, Object> result = new HashMap<>();

		Family family = familyService.findFamilyByUserId(userId);
		FamilyValidator.validateFamilyTid(family, tid);

		Family tfamily = familyService.findFamilyByUserId(tuserId);
		FamilyValidator.validateFamilyTid(tfamily, tid);

		FamilyMember tfamilyMember = findByUserId(tuserId);
		if (tfamilyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		User user = userService.findById(userId);
		if (user == null) {
			throw new FamilyExcepiton(FailCode.USER_NOT_EXIST);
		}

		User tuser = userService.findById(tuserId);
		if (tuser == null) {
			delete(tfamilyMember);
			throw new FamilyExcepiton(FailCode.USER_NOT_EXIST);
		}

		if (tfamilyMember.getMute() == 0) {
			throw new FamilyExcepiton(FailCode.APP, "对方没有被禁言");
		}

		FamilyMember familyMember = findByUserId(userId);
		if (familyMember == null || familyMember.getFamily_id().longValue() != tfamilyMember.getFamily_id()) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}

		if (family.getOwner_user_id() != userId.longValue()) {
			throw new FamilyExcepiton(FailCode.APP, "族长才可以解除禁言哟");
		}

		RedisLockUtil lockUtil = null;
		try {
			lockUtil = cacheService.getLock(Lock_memberMute + tuserId);
			setMemberMute(family, tfamilyMember, tuser, 0);
			deleteMemberMuteByPrex(family.getId(), userId, tuserId);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (lockUtil != null) {
				lockUtil.unlock();
			}
		}

		userService.formatMemberInfoCode(user, tuser, result);
		return result;
	}

	private void setMemberMute(Family family, FamilyMember member, User tuser, int mute) throws CFException {
		FamilyMember memberParam = new FamilyMember();
		memberParam.setId(member.getId());

		memberParam.setMute(mute);
		memberParam.setUpdate_time(new Timestamp(System.currentTimeMillis()));
		if (mute == 0) { // 解除禁言，重置时间
			memberParam.setMute_time(new Timestamp(System.currentTimeMillis() - 2000000l));
		}
		memberParam.setMute_num(0);
		this.update(memberParam);

		if (tuser.hasWyId()) {
			wyService.muteTeamMember(family.getTid(), family.getOwner_user_no(), tuser.getUser_no(), mute);
		}
	}

	private boolean addMemberRecord(Family family, User user, boolean auto) throws FamilyCaptionMaxCaption {
		FamilyMember familyMember = findByUserId(user.getId());
		if ((familyMember != null && familyMember.getFamily_id().longValue() == family.getId()) || (!auto && user.getIs_header().intValue() == 1)) {
			return false;
		}

		try {
			if (!lockFamilyCaption(family.getId(), auto)) {
				throw new FamilyCaptionMaxCaption(family.getId(), user.getId());
			}

			int deleteType = MemberDeleteEnum.invite.getType();
			try {
				if (familyMember != null) {
					if (!leaveFamily(familyMember, false, deleteType)) {
						unlockFamilyCaption(family.getId());
						return false;
					}
				}

				family = familyService.findById(family.getId());
				FamilyMember member = formateMember(family, user);
				save(member);
				return true;

			} catch (Exception e) {
				e.printStackTrace();
				unlockFamilyCaption(family.getId());
				return false;

			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;

		} 
	}

	private boolean lockFamilyCaption(Long fid, boolean auto) {
		Integer capacity = null;
		if (auto) {
			capacity = sysConfigService.getIntegerValue(SysConfigKeyEnum.create_family_user_num.name(), FamilyConstance.FAMILY_AUTO_SIZE);

		} else {
			capacity = sysConfigService.getIntegerValue(SysConfigKeyEnum.user_family_max.name(), FamilyConstance.FAMILY_CAPACITY);

		}

		Integer cnum = familyService.getFmember(fid);
		if (cnum >= capacity.intValue()) {
			log.info("=========================>cnum={}, capacity.intValue()={}", cnum, capacity.intValue());
			return false;
		}

		int newNum = 0;
		try {
			newNum = familyService.addFmebmer(fid, capacity.longValue());
			return newNum != -1;

		} catch (LockException e) {
			return false;

		}

	}

	private boolean unlockFamilyCaption(Long fid) {
		Integer cnum = familyService.getFmember(fid);
		if (cnum < 1) {
			return false;
		}

		int num = 0;
		try {
			num = familyService.reduceFmember(fid);
			return num != -1;

		} catch (LockException e) {
			return false;

		}
	}

	private FamilyMember formateMember(Family family, User user) {
		FamilyMember fm = new FamilyMember();
		fm.setFamily_id(family.getId());
		fm.setDevote(0l);
		fm.setDevote_sum(0l);
		fm.setIs_delete(0);
		fm.setMute(0);
		fm.setMute_num(null);
		fm.setMute_time(null);
		fm.setNick_name(user.getNick_name());
		fm.setUser_id(user.getId());
		fm.setUpdate_time(new Timestamp(System.currentTimeMillis()));
		fm.setCreate_time(new Timestamp(System.currentTimeMillis()));
		fm.setNocall(0);
		fm.setVersion("");
		fm.setShield(0);
		return fm;
	}

	private boolean leaveFamily(FamilyMember familyMember, boolean tick, int deleteType) throws CFException {
		if (familyMember == null) {
			return true;
		}

		Family family = familyService.findById(familyMember.getFamily_id());
		if (family == null) {
			baseDao.delete(familyMember);
			return true;
		}

		if (family.getOwner_user_id() == familyMember.getUser_id().longValue()) {
			throw new CFException(FailCode.APP, "族长不可以退出家族");
		}

		User user = userService.findById(familyMember.getUser_id());
		if (user.hasWyId()) {
			if (!tick) {
				wyService.leaveTeam(family.getTid(), user.getUser_no());

			} else {
				wyService.removeTeamMember(family.getTid(), family.getOwner_user_no(), user.getUser_no());

			}
		}

		FamilyMember memberParam = new FamilyMember();
		memberParam.setId(familyMember.getId());
		memberParam.setIs_delete(1);
		memberParam.setDeleteType(deleteType);
		memberParam.setVersion(UUID.randomUUID().toString());
		memberParam.setUpdate_time(new Timestamp(System.currentTimeMillis()));
		update(memberParam);
		unlockFamilyCaption(family.getId());
		return true;
	}

	private boolean canAutoAdd(User user) {
		if (user == null || !user.hasWyId()) {
			return false;
		}

		return true;
	}

	@Override
	public Map<String, Object> shieldFamily(Long uid, String tid, Integer shield) throws CFException {
		Map<String, Object> result = new HashMap<>();
		User user = userService.findById(uid);
		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		FamilyMember familyMember = findByUserId(uid);
		if (familyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		Family family = familyService.findById(familyMember.getFamily_id());
		FamilyValidator.validateFamilyTid(family, tid);
		String tips = null;
		boolean isHeader = user.getIs_header() != null && user.getIs_header() == 1;
		if (!isHeader) {
			FamilyMember memberParam = new FamilyMember();
			memberParam.setId(familyMember.getId());
			memberParam.setShield(shield);
			this.update(memberParam);
			wyService.shieldFamily(family, user.getUser_no(), shield);
		}
		if (shield == 1) {
			tips = isHeader ? tipsService.getShield(true) : tipsService.getShield(false);
		}else{
			refreshWy(user,family,familyMember);
		}
		FamilyMember member = findByUserId(uid);
		result.put("tips", tips);
		// 是否消息免打扰。0：否 1：是
		result.put("nocall", member.getNocall());
		// 是否家族屏蔽消息 0：否 1：是
		result.put("shield", member.getShield());
		return result;
	}

	private void refreshWy(User user, Family family, FamilyMember familyMember) {
		try {
//			 wyService.muteTeam(family.getTid(), user.getUser_no(), 0);
			 wyService.muteTeam(family.getTid(), user.getUser_no(), familyMember.getNocall());
			 wyService.muteTeamMember(family.getTid(), family.getOwner_user_no(), user.getUser_no(), familyMember.getMute());
		} catch (CFException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public Map<String, Object> getMember(Long uid, String tid) throws CFException {
		Map<String, Object> result = new HashMap<>();
		User user = userService.findById(uid);
		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		FamilyMember familyMember = findByUserId(uid);
		if (familyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		Family family = familyService.findById(familyMember.getFamily_id());
		FamilyValidator.validateFamilyTid(family, tid);

		FamilyMember member = findByUserId(uid);
		// 是否家族屏蔽消息 0：否 1：是
		result.put("shield", member.getShield());
		return result;
	}
	
	@Override
	public void checkFamilyMember() throws ParseException, IOException, CFException {
		List<Map<String, Object>> list = baseDao.findAllMember();
		if (list == null || list.isEmpty()) {
			return;
		}
		for (Map<String, Object> map : list) {
			RedisLockUtil lockUtil=null;
			try {
				Long userId = MapUtils.getLong(map, "id");
				String userNo = MapUtils.getString(map, "user_no");
				
				lockUtil = cacheService.getLock(KEY_PREFIX.move_user_.name() + userId);
				
				FamilyMember member=this.findByUserId(userId);
				if(member==null){
					log.info("checkFamilyMember========>member is null。userId={}",userId);
					continue;
				}
				Family family=familyService.findById(member.getFamily_id());
				if(family==null){
					log.info("checkFamilyMember========>family is null。userId={}",userId);
					continue;
				}
				wyService.checkTeamMember(family, member, userNo);

			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if (lockUtil != null) {
					lockUtil.unlock();
				}

			}

		}
	}

	@Override
	public Map<String, Object> updateMsgTime(Long uid, String tid) throws CFException {
		Map<String, Object> result = new HashMap<>();

		FamilyMember familyMember = findByUserId(uid);
		if (familyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		Family family = familyService.findFamilyByUserId(uid);
		FamilyValidator.validateFamilyTid(family, tid);

		long timeMillis = System.currentTimeMillis();
		
		FamilyMember memberParam=new FamilyMember();
		memberParam.setId(familyMember.getId());
		memberParam.setMsg_time(new Timestamp(timeMillis));
		update(memberParam);
		result.put("msg_time", memberParam.getMsg_time().getTime());
		
		return result;
	}

	@Override
	public Map<String, Object> getMsgTime(Long uid, String tid)throws CFException {
		Map<String, Object> result = new HashMap<>();
		
		FamilyMember familyMember = findByUserId(uid);
		if (familyMember == null) {
			throw new FamilyExcepiton(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}
		Timestamp msg_time = familyMember.getMsg_time();
		Timestamp create_time = familyMember.getCreate_time();
		
		result.put("msg_time",msg_time== null ?create_time : msg_time);
		return result;
	}
}